
const axios = require('axios')

exports.use = function (router, hanlde, options = {}) {
  router.get('/oauth/github/login', ctx => {
    const { clientId, callbackUrl } = ctx.config ? ctx.config.github : options

    ctx.redirect(`http://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${callbackUrl}&scope=user`, '', 302)
  })

  router.get('/oauth/github/callback', async (ctx, next) => {
    const code = ctx.query.code
    // const state = ctx.query.state

    const { clientId, clientSecret, callbackUrl } = ctx.config ? ctx.config.github : options

    if (!code) {
      ctx.body = 'code 参数必须'
      return
    }

    const tokenRes = await axios.post('https://github.com/login/oauth/access_token', {
      client_id: clientId,
      client_secret: clientSecret,
      redirect_uri: callbackUrl,
      code: code
    }, {
      headers: {
        accept: 'application/json'
      }
    })

    // eslint-disable-next-line camelcase
    const { access_token } = tokenRes.data

    // eslint-disable-next-line camelcase
    if (!access_token) {
      ctx.body = tokenRes.data
      return
    }

    const userRes = await axios.get('https://api.github.com/user', {
      params: {
        access_token: access_token
      }
    })

    if (!userRes.data.login) {
      ctx.body = userRes.data
      return
    }

    ctx.state.github = {
      access_token: access_token,
      user: userRes.data
    }

    await hanlde(ctx, next)
  })
}
